public class Solution8 {
    //931. 下降路径最小和
    public int minFallingPathSum(int[][] matrix) {
        int n = matrix.length;
        int[][] dp = new int[n][n];
        for (int i = 0; i < n; i++) {
            dp[0][i] = matrix[0][i];   //初始化第一行数据
        }
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < n; j++) {
                dp[i][j] = dp[i-1][j] + matrix[i][j];
                if (j-1 >= 0) {
                    dp[i][j] = Math.min(dp[i][j],dp[i-1][j-1] + matrix[i][j]);
                }

                if (j + 1 < n) {
                    dp[i][j] = Math.min(dp[i][j],dp[i-1][j+1] + matrix[i][j]);
                }
            }
        }
        int ret = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            ret = Math.min(ret,dp[n-1][i]);
        }
        return ret;
    }
}
